package com.xxx.nio.write;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * 写入内容过多问题 Server端
 */
@Slf4j
public class Server {

    public static void main(String[] args) throws IOException {
        // 1.创建Server端的SocketChannel，并将其注册到Selector上
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);  // 配置为非阻塞模式
        ssc.bind(new InetSocketAddress(8080));

        // 2.创建一个selector，用来管理多个channel
        Selector selector = Selector.open();
        SelectionKey sscKey = ssc.register(selector, SelectionKey.OP_ACCEPT, null);// 将Server端的channel注册到Selector上，返回注册结果key
        log.debug("register sscKey:{}", sscKey);

        int count = 0;
        while (true) {
            // 3.select()方法会一直阻塞，直到监听的事件到来
            selector.select();  // 阻塞
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();  // selectedKeys包含了内部所有的事件
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if(key.isAcceptable()) {
                    ssc = (ServerSocketChannel) key.channel();
                    SocketChannel sc = ssc.accept();  // 监听的是accept()事件
                    sc.configureBlocking(false);    // 配置为非阻塞模式
                    SelectionKey scKey = sc.register(selector, 0, null);

                    // 向客户端 发送大量 数据
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < 30000000; i++) {
                        sb.append("a");
                    }
                    ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());
//                    while (buffer.hasRemaining()) {
//                        int write = sc.write(buffer);
//                        System.out.println(write);
//                        count += write;
//                        System.out.println("count:" + count);
//                    }

                    // 先写一次 ，没写完有剩余字节 将关注写事件，将未写完数据挂到 scKey
                    int write = sc.write(buffer);
                    System.out.println(write);
                    count += write;

                    // 判断buffer中是否还有数据
                    if(buffer.hasRemaining()) {
                        scKey.interestOps(scKey.interestOps() + SelectionKey.OP_WRITE);  // 在原来关注的事件上增加关注可写事件
                        scKey.attach(buffer); // 将未写完的buffer挂载到scKey里
                    }
                } else if (key.isWritable()) {  // 可写事件
                    // 从key里取出attachment
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    SocketChannel sc = (SocketChannel) key.channel();
                    int write = sc.write(buffer);
                    System.out.println(write);
                    count += write;
                    System.out.println("count:" + count);
                    // 判断是否写完，如果写完了，需要将buffer取消挂载（节省内存），并取消监听可写事件
                    if(!buffer.hasRemaining()) {
                        sscKey.attach(null);
                        sscKey.interestOps(sscKey.interestOps() - SelectionKey.OP_WRITE);
                    }
                }
            }
        }
    }
}
